package com.contractpage.mybatisUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.contractpage.util.PropertiesLoader;

public class EntityUtil {
	 
    /**
     **********************************使用前必读*******************
     **
     ** 使用前请将moduleName更改为自己模块的名称即可（一般情况下与数据库名一致），其他无须改动。
     **
     ***********************************************************
     */
 
    private final String type_char = "char";
 
    private final String type_date = "date";
 
    private final String type_timestamp = "timestamp";
 
    private final String type_int = "int";
 
    private final String type_bigint = "bigint";
 
    private final String type_text = "text";
 
    private final String type_bit = "bit";
 
    private final String type_decimal = "decimal";
 
    private final String type_blob = "blob";
 
    private static String base_path = "E:/soft/hx/mybatis/xml";
    
    private static String service_path = base_path + "/service";
 
    private static String serviceImpl_path = base_path + "/service/impl";
    
    private static String action_path = base_path + "/action";
    
    //private final String moduleName = "group"; // 对应模块名称（根据自己模块做相应调整!!!务必修改^_^）
 
    private  String bean_path = base_path + "/entity_bean";
 
    private String html_path = base_path + "/html";
    
    private  String mapper_path = base_path + "/mapper/interface";
 
    private static  String xml_path = base_path + "/mapper/xml";
 
/*    private final String bean_package = "com.contractpage.ec.dao";
 
    private final static String mapper_package = "com.contractpage.ec.dao";*/
 
    private final static String projectName = "Core";
    private String driverName;
    
    private String filterCloums = "id,upuser,update";//需要过滤的字段
    
    private List<String> filterCloumsArray = new ArrayList<String>();
    
    private String user;
 
    private String password;
 
    private String url;
 
    private static String tableName = null;
 
    private static String beanName = null;
 
    private static String mapperName = null;
    
    private static String schem;
    
    private static PropertiesLoader loader = new PropertiesLoader("config.properties");
    
    private static String jdbcType;
    
    private static String alltablesSql;
    
    private static Connection conn = null;
 
    {
    	jdbcType = loader.getProperty("jdbc.type");
    	url = loader.getProperty("db.crm.url");
    	user = loader.getProperty("db.crm.user");
    	password = loader.getProperty("db.crm.pwd");
    	for(String str:filterCloums.split(",")){
    		filterCloumsArray.add(str);
    	}
    	if("mysql".equals(jdbcType)){
    		driverName = "com.mysql.jdbc.Driver";
    		alltablesSql = "show tables";
    		String[] strs = url.split("/");
    		String str = strs[strs.length - 1];
    		schem = str.substring(0, str.indexOf("?"));
    		System.out.println(schem);
    		
    	}else{
    		driverName = "oracle.jdbc.driver.OracleDriver";
    		alltablesSql = "select table_name from all_tables where owner = '" + user + "'";
    	}
        try {
			Class.forName(driverName);
			conn = DriverManager.getConnection(url, user, password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    @Test
    public void test(){
    	System.out.println(loader.getProperty("db.crm.url"));
    	List<String> tables;
		try {
			tables = getTables();
			generate(tables, conn, beanName);
		}  catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    	
    }
    
 
    private void init() throws ClassNotFoundException, SQLException {
    	String jdbcType = loader.getProperty("jdbc.type");
    	if("mysql".equals(jdbcType)){
    		driverName = "com.mysql.jdbc.Driver";
    	}else{
    		driverName = "oracle.jdbc.driver.OracleDriver";
    	}
    	url = loader.getProperty("db.crm.url");
    	user = loader.getProperty("db.crm.user");
    	password = loader.getProperty("db.crm.pwd");
        Class.forName(driverName);
        conn = DriverManager.getConnection(url, user, password);
    }
 
 
    /**
     *  获取所有的表
     *
     * @return
     * @throws SQLException 
     */
    private List<String> getTables() throws SQLException {
        List<String> tables = new ArrayList<String>();
        PreparedStatement pstate = conn.prepareStatement(alltablesSql);
        ResultSet results = pstate.executeQuery();
        while ( results.next() ) {
            tableName = "mysql".equals(jdbcType)?results.getString(1):results.getString("table_name");
            tables.add(tableName);
        }
        return tables;
    }
 
 
    private static void processTable( String table ) {
        StringBuffer sb = new StringBuffer();
        String tableNew = table.toLowerCase();
        String[] tables = tableNew.split("_");
        String temp = null;
        for ( int i = 0 ; i < tables.length ; i++ ) {
            temp = tables[i].trim();
            sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1));
        }
        beanName = sb.toString();
        System.out.println("beanName ---- "+beanName);
        mapperName = projectName+"_"+beanName.toLowerCase();
    }
 
 
    private String processType( String type ) {
        if ( type.indexOf(type_char) > -1 ) {
            return "String";
        } else if ( type.indexOf(type_bigint) > -1 ) {
            return "Long";
        } else if ( type.indexOf(type_int) > -1 ) {
            return "Integer";
        } else if ( type.indexOf(type_date) > -1 ) {
            return "java.util.Date";
        } else if ( type.indexOf(type_text) > -1 ) {
            return "String";
        } else if ( type.indexOf(type_timestamp) > -1 ) {
            return "java.util.Date";
        } else if ( type.indexOf(type_bit) > -1 ) {
            return "Boolean";
        } else if ( type.indexOf(type_decimal) > -1 || "number".equals(type)) {
            return "java.math.BigDecimal";
        } else if ( type.indexOf(type_blob) > -1 ) {
            return "byte[]";
        }
        return null;
    }
 
 
    private static String processField( String field ) {
        StringBuffer sb = new StringBuffer(field.length());
        //field = field.toLowerCase();
        String[] fields = field.split("_");
        String temp = null;
        sb.append(fields[0]);
        for ( int i = 1 ; i < fields.length ; i++ ) {
            temp = fields[i].trim();
            sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1));
        }
        return sb.toString();
    }
 
 
    /**
     *  将实体类名首字母改为小写
     *
     * @param beanName
     * @return 
     */
    private String processResultMapId( String beanName ) {
        return beanName.toLowerCase();
    }
 
 
    /**
     *  构建类上面的注释
     *
     * @param bw
     * @param text
     * @return
     * @throws IOException 
     */
    private BufferedWriter buildClassComment( BufferedWriter bw, String text ) throws IOException {
        bw.newLine();
        bw.newLine();
        bw.write("/**");
        bw.newLine();
        bw.write(" * ");
        bw.newLine();
        bw.write(" * " + text);
        bw.newLine();
        bw.write(" * ");
        bw.newLine();
        bw.write(" **/");
        return bw;
    }
 
 
    /**
     *  构建方法上面的注释
     *
     * @param bw
     * @param text
     * @return
     * @throws IOException 
     */
    private BufferedWriter buildMethodComment( BufferedWriter bw, String text ) throws IOException {
        bw.newLine();
        bw.write("\t/**");
        bw.newLine();
        bw.write("\t * ");
        bw.newLine();
        bw.write("\t * " + text);
        bw.newLine();
        bw.write("\t * ");
        bw.newLine();
        bw.write("\t **/");
        return bw;
    }
 
    /**
     *  生成实体类
     *
     * @param columns
     * @param types
     * @param comments
     * @throws IOException 
     */
    public void buildEntityBean( List<String> columns, List<String> types, List<String> comments, String tableComment )
        throws IOException {
    	System.out.println("buildEntityBean");
        File folder = new File(bean_path);
        if ( !folder.exists() ) {
            folder.mkdir();
        }
        String basepackage = "com." + schem + ".ec.entity";
        File beanFile = new File(bean_path, beanName + ".java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile)));
        bw.write("package " + basepackage + ";");
        bw.newLine();
        bw.write("import com." + schem + ".common.persistence.DataEntity;");
        bw.newLine();
        //bw.write("import lombok.Data;");
        //      bw.write("import javax.persistence.Entity;");
        bw = buildClassComment(bw, tableComment);
        bw.newLine();
        bw.write("@SuppressWarnings(\"serial\")");
        bw.newLine();
        //      bw.write("@Entity");
        //bw.write("@Data");
        //bw.newLine();
        bw.write("public class " + beanName + " extends DataEntity<" + beanName + "> {");
        bw.newLine();
        bw.newLine();
        String tempField = null;
        String _tempField = null;
        String tempType = null;
        int size = columns.size();
        for(int i = 0 ; i < size ; i++){
        	if(filterCloumsArray.contains(columns.get(i))){
        		continue;
        	};
        	tempType = processType(types.get(i).toLowerCase());
        	bw.write("\tprivate " + tempType + " " + columns.get(i) + ";");
        	bw.newLine();
        }
        bw.newLine();
        // 生成get 和 set方法
        
        for ( int i = 0 ; i < size ; i++ ) {
        	if(filterCloumsArray.contains(columns.get(i))){
        		continue;
        	};
            tempType = processType(types.get(i).toLowerCase());
            System.out.println(types.get(i)+"----"+tempType);
            _tempField = processField(columns.get(i));
            System.out.println("_tempField:"+_tempField);
            tempField = _tempField.substring(0, 1).toUpperCase() + _tempField.substring(1);
            bw.newLine();
            bw.write("\tpublic void set" + tempField + "(" + tempType + " " + _tempField + "){");
            bw.newLine();
            bw.write("\t\tthis." + _tempField + " = " + _tempField + ";");
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();
            bw.write("\tpublic " + tempType + " get" + tempField + "(){");
            bw.newLine();
            bw.write("\t\treturn this." + _tempField + ";");
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
        }
        bw.newLine();
        bw.write("}");
        bw.newLine();
        System.out.println(bw.toString());
        bw.flush();
        bw.close();
    }
    
    private void buildHtml(List<String> columns,List<String> comments) throws IOException{
    	System.out.println("buildEntityBean");
        File folder = new File(html_path);
        if ( !folder.exists() ) {
            folder.mkdir();
        }
        File beanFile = new File(html_path, beanName + ".html");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile)));
        bw.newLine();
        String bean = beanName.substring(1);
        bean = beanName.substring(0, 1).toLowerCase() + bean;
        /**
         * <script src="js/jquery-3.2.1.min.js"></script>
	<script type="text/javascript" src="lib/layer/2.4/layer.js"></script>
	<script src="js/select.jquery.js"></script>
	<script type="text/javascript" src = "js/util.js"></script>
	<script type="text/javascript" src = "js/table.js"></script>
         */
        bw.write("\t\t<script src=\"js/jquery-3.2.1.min.js\"></script>");
        bw.newLine();
        bw.write("\t\t<script type=\"text/javascript\" src=\"lib/layer/2.4/layer.js\"></script>");
        bw.newLine();
        bw.write("\t\t<script src=\"js/select.jquery.js\"></script>");
        bw.newLine();
        bw.write("\t\t<script type=\"text/javascript\" src = \"js/util.js\"></script>");
        bw.newLine();
        bw.write("\t\t<script type=\"text/javascript\" src = \"js/table.js\"></script>");
        bw.newLine();
        bw.write("\t\t<table  class=\"content-table-two\" cellspacing=\"0\" cellpadding=\"0\" datatable = \"true\" dataAction = \"/" + bean + "/findList\">");
        bw.newLine();
        bw.write("\t\t\t<tbody style = \"display:none;\">");
        bw.newLine();
        for(int i = 0 ; i < columns.size() ; i++){
        	bw.write("\t\t\t\t<th title = \"" + comments.get(i) + "\" name = \"" + columns.get(i) + "\" type = \"string\"></th>");
        	bw.newLine();
        }
        bw.write("\t\t\t</tbody>");
        bw.newLine();
        bw.write("\t\t</table>");
        bw.flush();
        bw.close();
    }
    
    /**
     *  构建Service文件
     *
     * @throws IOException 
     */
    private void buildService() throws IOException {
        File folder = new File(service_path);
        if ( !folder.exists() ) {
            folder.mkdirs();
        }
        File mapperFile = new File(service_path, beanName + "Service" + ".java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperFile), "utf-8"));
        bw.write("package com." + schem + ".ec.service;");
        bw.newLine();
        bw.newLine();
        bw.write("import com." + schem + ".ec.entity." + beanName + ";");
        bw.newLine();
        bw.newLine();
        bw = buildClassComment(bw, beanName + "Service" + "数据库操作接口类");
        bw.newLine();
        bw.newLine();
        //      bw.write("public interface " + mapperName + " extends " + mapper_extends + "<" + beanName + "> {");
        bw.write("public interface " + beanName + "Service" + " extends CurdService<" + beanName + ">{");
        bw.newLine();
        bw.write("}");
        bw.flush();
        bw.close();
    }
    
    /**
     *  构建ServiceImpl文件
     * @throws IOException 
     */
    private void buildServiceImpl() throws IOException {
        File folder = new File(serviceImpl_path);
        if ( !folder.exists() ) {
            folder.mkdirs();
        }
        String bean = beanName.substring(1);
        bean = beanName.substring(0, 1).toLowerCase() + bean;
        File mapperFile = new File(serviceImpl_path, beanName + "ServiceImpl" + ".java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperFile), "utf-8"));
        bw.write("package com." + schem + ".ec.service.impl;");
        bw.newLine();
        bw.newLine();
        bw.newLine();
        bw.write("import java.util.List;");
        bw.newLine();
        bw.write("import org.springframework.beans.factory.annotation.Autowired;");
        bw.newLine();
        bw.write("import org.springframework.stereotype.Service;");
        bw.newLine();
        bw.write("import com." + schem + ".common.persistence.Page;");
        bw.newLine();
        bw.write("import com." + schem + ".ec.dao." + beanName + "Dao;");
        bw.newLine();
        bw.write("import com." + schem + ".ec.service." + beanName + "Service;");
        bw.newLine();
        bw.write("import com." + schem + ".ec.entity." + beanName + ";");
        bw.newLine();
        bw.newLine();
        bw = buildClassComment(bw, beanName + "ServiceImpl" + "数据库操作接口类");
        bw.newLine();
        bw.newLine();
        //      bw.write("public interface " + mapperName + " extends " + mapper_extends + "<" + beanName + "> {");
        bw.write("@Service");
        bw.newLine();
        bw.write("public class " + beanName + "ServiceImpl" + " implements " + beanName + "Service{");
        bw.newLine();
        bw.write("\t@Autowired");
        bw.newLine();
        bw.write("\tprivate " + beanName + "Dao" + " " + bean + "Dao;");
        bw.newLine();
        bw.write("\t@Override");
        bw.newLine();
        bw.write("\tpublic Page<" + beanName + "> findList(Page<" + beanName + "> page," + beanName + " entity){");
        bw.newLine();
        bw.write("\t\tentity.setPage(page);");
        bw.newLine();
        bw.write("\t\tpage.setList(" + bean + "Dao.findList(entity));");
        bw.newLine();
        bw.write("\t\treturn page;");
        bw.newLine();
        bw.write("\t}");
        bw.newLine();
        bw.write("\t@Override");
        bw.newLine();
        bw.write("\tpublic int insert(" + beanName + " entity){");
        bw.newLine();
        bw.write("\t\tentity.preInsert(\"\");");
        bw.newLine();
        bw.write("\t\treturn " + bean + "Dao.insert(entity);");
        bw.newLine();
        bw.write("\t}");
        bw.newLine();
        bw.write("\t@Override");
        bw.newLine();
        bw.write("\tpublic int update(" + beanName + " entity){");
        bw.newLine();
        bw.write("\t\tentity.preUpdate();");
        bw.newLine();
        bw.write("\t\treturn " + bean + "Dao.update(entity);");
        bw.newLine();
        bw.write("\t}");
        bw.newLine();
        bw.write("\t@Override");
        bw.newLine();
        bw.write("\tpublic int delete(" + beanName + " entity){");
        bw.newLine();
        bw.write("\t\t return " + bean + "Dao.delete(entity);");
        bw.newLine();
        bw.write("\t}");
        bw.newLine();
        bw.write("}");
        bw.flush();
        bw.close();
    }
    
    /**
     *  
     * @throws IOException
     */
    private void buildAction() throws IOException{
    	File folder = new File(action_path);
        if ( !folder.exists() ) {
            folder.mkdirs();
        }
        String bean = beanName.substring(1);
        bean = beanName.substring(0, 1).toLowerCase() + bean;
        File mapperFile = new File(action_path, beanName + "Controller" + ".java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperFile), "utf-8"));
        bw.write("package com." + schem + ".ec;");
        bw.newLine();
        bw.newLine();
        bw.write("import javax.servlet.http.HttpServletRequest;");
        bw.newLine();
        bw.write("import javax.servlet.http.HttpServletResponse;");
        bw.newLine();
        bw.write("import org.springframework.beans.factory.annotation.Autowired;");
        bw.newLine();
        bw.write("import org.springframework.stereotype.Controller;");
        bw.newLine();
        bw.write("import org.springframework.ui.Model;");
        bw.newLine();
        bw.write("import org.springframework.web.bind.annotation.RequestMapping;");
        bw.newLine();
        bw.write("import org.springframework.web.bind.annotation.ResponseBody;");
        bw.newLine();
        bw.write("import com." + schem + ".common.persistence.Page;");
        bw.newLine();
        bw.write("import com." + schem + ".ec.entity." + beanName + ";");
        bw.newLine();
        bw.write("import com." + schem + ".ec.service." + beanName + "Service;");
        bw.newLine();
        bw.write("import com." + schem + ".util.StringUtils;");
        bw.newLine();
        bw.newLine();
        bw.write("@Controller");
        bw.newLine();
        bw.write("@RequestMapping(value = \"" + bean + "\")");
        bw.newLine();
        bw.write("public class "+ beanName +"Controller {");
        bw.newLine();
        bw.newLine();
        bw.write("\t@Autowired");
        bw.newLine();
        bw.write("\tprivate " + beanName + "Service " + bean + "Service;");
        bw.newLine();
        bw.newLine();
        bw.write("\t@RequestMapping(value = \"findList\")");
        bw.newLine();
        bw.write("\t@ResponseBody");
        bw.newLine();
        bw.write("\tpublic Object findList(" + beanName + " entity, HttpServletRequest request, HttpServletResponse response, Model model){");
        bw.newLine();
        bw.write("\t\tPage<" + beanName + "> page = new Page<" + beanName + ">(request,response);");
        bw.newLine();
        bw.write("\t\treturn  " + bean + "Service.findList(page, entity);");
        bw.newLine();
        bw.write("\t}");
        bw.newLine();
        bw.write("\t@RequestMapping(value = \"save\")");
        bw.newLine();
        bw.write("\t@ResponseBody");
        bw.newLine();
        bw.write("\tpublic Object save(" + beanName + " entity, HttpServletRequest request, HttpServletResponse response, Model model){");
        bw.newLine();
        bw.write("\t\tint i = StringUtils.isEmpty(entity.getId())?" + bean + "Service.insert(entity):" + bean + "Service.update(entity);");
        bw.newLine();
        bw.write("\t\treturn i;");
        bw.newLine();
        bw.write("\t}");
        bw.newLine();
        bw.write("\t@RequestMapping(value = \"delete\")");
        bw.newLine();
        bw.write("\t@ResponseBody");
        bw.newLine();
        bw.write("\tpublic Object delete(" + beanName + " entity, HttpServletRequest request, HttpServletResponse response, Model model){");
        bw.newLine();
        bw.write("\t\treturn " + bean + "Service.delete(entity);");
        bw.newLine();
        bw.write("\t}");
        bw.newLine();
        bw.write("}");
        bw.flush();
        bw.close();
        
    }
    
    /**
     *  构建Mapper文件
     *
     * @throws IOException 
     */
    private void buildMapper() throws IOException {
        File folder = new File(mapper_path);
        if ( !folder.exists() ) {
            folder.mkdirs();
        }
        File mapperFile = new File(mapper_path, beanName + "Dao" + ".java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperFile), "utf-8"));
        bw.write("package com." + schem + ".ec.dao;");
        bw.newLine();
        bw.newLine();
        bw.write("import com." + schem + ".ec.entity." + beanName + ";");
        bw.newLine();
        bw.write("import com." + schem + ".common.persistence.annotation.MyBatisDao;");
        bw.newLine();
        bw.write("import com."+ schem +".common.persistence.CrudDao;");
        bw.newLine();
        bw = buildClassComment(bw, beanName + "Dao" + "数据库操作接口类");
        bw.newLine();
        bw.newLine();
        bw.write("@MyBatisDao");
        bw.newLine();
        bw.write("public interface " + beanName + "Dao" + " extends CrudDao<" + beanName + ">{");
        bw.newLine();
        bw.write("}");
        bw.flush();
        bw.close();
    }
 
 
    /**
     *  构建实体类映射XML文件
     *
     * @param columns
     * @param types
     * @param comments
     * @throws IOException 
     */
    private static void buildMapperXml( List<String> columns, List<String> types, List<String> comments) throws IOException {
        File folder = new File(xml_path);
        if ( !folder.exists() ) {
            folder.mkdirs();
        }
 
        File mapperXmlFile = new File(xml_path, beanName + "Dao" + ".xml");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperXmlFile),"UTF-8"));
        bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        bw.newLine();
        bw.write("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" ");
        bw.newLine();
        bw.write("    \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">");
        bw.newLine();
        bw.write("<mapper namespace=\"com." + schem + ".ec.dao." + beanName + "Dao\">");
        bw.newLine();
        bw.newLine();
        buildSQL(bw, columns, types);
 
        bw.write("</mapper>");
        bw.flush();
        bw.close();
    }
 
 
    private static void buildSQL( BufferedWriter bw, List<String> columns, List<String> types ) throws IOException {
        int size = columns.size();
        // 通用结果列
        bw.write("\t<!-- 通用查询结果列-->");
        bw.newLine();
        bw.write("\t<sql id=\"columns\">");
        bw.newLine();
 
        for ( int i = 0 ; i < size ; i++ ) {
            bw.write("\t\t" + "a." +columns.get(i));
            if ( i != size - 1 ) {
                bw.write(",");
            }
            bw.newLine();
        }
 
        bw.newLine();
        bw.write("\t</sql>");
        bw.newLine();
        bw.newLine();
 
 
        // 查询（根据主键ID查询）
        bw.write("\t<!-- 查询 -->");
        bw.newLine();
        bw.write("\t<select id=\"findList\" parameterType=\"com." + schem + ".ec.entity." + beanName + "\" resultType = \"com." + schem + ".ec.entity." + beanName + "\">");
        bw.newLine();
        bw.write("\t\t SELECT");
        bw.newLine();
        bw.write("\t\t <include refid=\"columns\" />");
        bw.newLine();
        bw.write("\t\t FROM " + tableName + " a");
        bw.newLine();
        bw.write("\t\t WHERE  1 = 1");
        bw.newLine();
        for(int i = 0 ; i < columns.size() ; i ++){
        	bw.write("\t\t <if test = \""+columns.get(i) + " != null and " + columns.get(i) +" != ''\">");
        	bw.newLine();
        	bw.write( "\t\t\t and a." + columns.get(i) + " = #{" + columns.get(i) + "}");
        	bw.newLine();
        	bw.write("\t\t </if>");
            bw.newLine();
        }
        
        bw.write("\t</select>");
        bw.newLine();
        bw.newLine();
        // 查询完
 
 
        // 删除（根据主键ID删除）
        bw.write("\t<!--删除-->");
        bw.newLine();
        bw.write("\t<delete id=\"delete\" parameterType=\"com." + schem + ".ec.entity." + beanName + "\">");
        bw.newLine();
        bw.write("\t\t DELETE FROM " + tableName);
        bw.newLine();
        bw.write("\t\t WHERE  1 = 1");
        bw.newLine();
        for(int i = 0 ; i < columns.size() ; i ++){
        	bw.write("\t\t <if test = \""+columns.get(i) + " != null and " + columns.get(i) +" != ''\">");
        	bw.newLine();
        	bw.write( "\t\t\t and " + columns.get(i) + " = #{" + columns.get(i) + "}");
        	bw.newLine();
        	bw.write("\t\t </if>");
            bw.newLine();
        }
        bw.write("\t</delete>");
        bw.newLine();
        bw.newLine();
        // 删除完
 
 
        // 添加insert方法
        /*bw.write("\t<!-- 添加 -->");
        bw.newLine();
        bw.write("\t<insert id=\"insert\" " + ">");
        bw.newLine();
        bw.write("\t\t INSERT INTO " + tableName);
        bw.newLine();
        bw.write(" \t\t(");
        for ( int i = 0 ; i < size ; i++ ) {
            bw.write(columns.get(i));
            if ( i != size - 1 ) {
                bw.write(",");
            }
        }
        bw.write(") ");
        bw.newLine();
        bw.write("\t\t VALUES ");
        bw.newLine();
        bw.write(" \t\t(");
        for ( int i = 0 ; i < size ; i++ ) {
            bw.write("#{" + columns.get(i) + "}");
            if ( i != size - 1 ) {
                bw.write(",");
            }
        }
        bw.write(") ");
        bw.newLine();
        bw.write("\t</insert>");
        bw.newLine();
        bw.newLine();*/
        // 添加insert完
 
 
        //---------------  insert方法（匹配有值的字段）
        bw.write("\t<!-- 添加 （匹配有值的字段）-->");
        bw.newLine();
        bw.write("\t<insert id=\"insert\"  parameterType=\"com." + schem + ".ec.entity." + beanName + "\">");
        bw.newLine();
        bw.write("\t\t INSERT INTO " + tableName);
        bw.newLine();
        bw.write("\t\t <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\" >");
        bw.newLine();
 
        String tempField = null;
        for ( int i = 0 ; i < size ; i++ ) {
            tempField = columns.get(i);
            bw.write("\t\t\t<if test=\"" + tempField + " != null and "+tempField+" != '' \">");
            bw.newLine();
            bw.write("\t\t\t\t " + columns.get(i));
            if(i < size -1){
            	bw.write(",");
            }
            bw.newLine();
            bw.write("\t\t\t</if>");
            bw.newLine();
        }
 
        bw.newLine();
        bw.write("\t\t </trim>");
        bw.newLine();
 
        bw.write("\t\t <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\" >");
        bw.newLine();
 
        tempField = null;
        for ( int i = 0 ; i < size ; i++ ) {
            tempField = processField(columns.get(i));
            bw.write("\t\t\t<if test=\"" + columns.get(i) + " !=null and "+columns.get(i)+" != ''\">");
            bw.newLine();
            bw.write("\t\t\t\t #{" + columns.get(i) + "}");
            if(i < size -1){
            	bw.write(",");
            }
            bw.newLine();
            bw.write("\t\t\t</if>");
            bw.newLine();
        }
 
        bw.write("\t\t </trim>");
        bw.newLine();
        bw.write("\t</insert>");
        bw.newLine();
        bw.newLine();
        //---------------  完毕
 
 
        // 修改update方法
        bw.write("\t<!-- 修 改-->");
        bw.newLine();
        bw.write("\t<update id=\"update\"  parameterType=\"com." + schem + ".ec.entity." + beanName + "\">");
        bw.newLine();
        bw.write("\t\t UPDATE " + tableName + "  a");
        bw.newLine();
        bw.write(" \t\t <set> ");
        bw.newLine();
        tempField = null;
        for ( int i = 1 ; i < size ; i++ ) {
            tempField = columns.get(i);
            bw.write("\t\t\t<if test=\"" + tempField + " != null\">");
            bw.newLine();
            bw.write("\t\t\t\t a." + columns.get(i) + " = #{" + tempField + "},");
            bw.newLine();
            bw.write("\t\t\t</if>");
            bw.newLine();
        }
        bw.newLine();
        bw.write(" \t\t </set>");
        bw.newLine();
        bw.write("\t\t WHERE 1 = 1");
        bw.newLine();
        for ( int i = 0 ; i < size ; i++ ) {
            tempField = columns.get(i);
            bw.write("\t\t\t<if test=\"" + tempField + " != null\">");
            bw.newLine();
            bw.write("\t\t\t\t and  a." + columns.get(i) + " = #{" + tempField + "}");
            bw.newLine();
            bw.write("\t\t\t</if>");
            bw.newLine();
        }
        bw.newLine();
        bw.write("\t</update>");
        bw.newLine();
        bw.newLine();
        // update方法完毕
 
        // ----- 修改（匹配有值的字段）
       /* bw.write("\t<!-- 修 改-->");
        bw.newLine();
        bw.write("\t<update id=\"updateByPrimaryKey\" " + ">");
        bw.newLine();
        bw.write("\t\t UPDATE " + tableName);
        bw.newLine();
        bw.write("\t\t SET ");
 
        bw.newLine();
        tempField = null;
        for ( int i = 1 ; i < size ; i++ ) {
            tempField = columns.get(i);
            bw.write("\t\t\t " + columns.get(i) + " = #{" + columns.get(i) + "}");
            if ( i != size - 1 ) {
                bw.write(",");
            }
            bw.newLine();
        }
 
        bw.write("\t\t WHERE " + columns.get(0) + " = #{" + columns.get(0) + "}");
        bw.newLine();
        bw.write("\t</update>");
        bw.newLine();
        bw.newLine();*/
    }
 
 
    /**
     *  获取所有的数据库表注释
     *
     * @return
     * @throws SQLException 
     */
    private static Map<String, String> getTableComment(Connection conn) throws SQLException {
        Map<String, String> maps = new HashMap<String, String>();
        String sql = "mysql".equals(jdbcType)?"SELECT TABLE_NAME,TABLE_COMMENT FROM information_schema.TABLES WHERE table_schema='mammothcode';":"select * from user_col_comments";
        PreparedStatement pstate = conn.prepareStatement(sql);
        ResultSet results = pstate.executeQuery();
        while ( results.next() ) {
            String tableName = results.getString("table_name");
            String comment = results.getString("comments");
            maps.put(tableName, comment);
        }
        return maps;
    }
 
 
    public void generate(List<String> tables , Connection conn , String xml_path) throws ClassNotFoundException, SQLException, IOException {
        PreparedStatement pstate = null;
        Map<String, String> tableComments = getTableComment(conn);
        List<String> columns = null;
        List<String> types = null;
        List<String> comments = null;
        for ( String table : tables ) {
        	String sql = "mysql".equals(jdbcType)?"select * from INFORMATION_SCHEMA.Columns where table_schema='" + schem + "' and table_name='" + table + "'":"select * from user_tab_columns where Table_Name='" + table + "'";
        	columns = new ArrayList<String>();
            types = new ArrayList<String>();
            comments = new ArrayList<String>();
            pstate = conn.prepareStatement(sql);
            ResultSet results = pstate.executeQuery();
            while ( results.next() ) {
                columns.add(results.getString("column_name"));
                types.add(results.getString("data_type"));
                comments.add(results.getString("column_comment"));
            }
            tableName = table;
            processTable(table);
            String tableComment = tableComments.get(tableName);
            buildEntityBean(columns, types, comments, tableComment);
            buildMapper();
            buildMapperXml(columns, types, comments);
            buildServiceImpl();
            buildService();
            buildAction();
            buildHtml(columns,comments);
        }
        conn.close();
    }
 
 
   /* public static void main( String[] args ) {
        try {
        	generate();
            // 自动打开生成文件的目录
            Runtime.getRuntime().exec("cmd /c start explorer D:\\");
        } catch ( ClassNotFoundException e ) {
            e.printStackTrace();
        } catch ( SQLException e ) {
            e.printStackTrace();
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }
    */
}
